package com.lyn.serialport.control;

/*
 *****************************************
 *项目名称:aijiu
 *@Author jzb
 *创建时间 20211103 09:44
 *
 *****************************************
 */public class ByteUtil {
    public static String bytes2hex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        String tmp = null;
        for (byte b : bytes) {
            // 将每个字节与0xFF进行与运算，然后转化为10进制，然后借助于Integer再转化为16进制
            tmp = Integer.toHexString(0xFF & b);
            if (tmp.length() == 1) {
                sb.append(" 0").append(tmp);
            }else {
                sb.append(" ").append(tmp);
            }
        }
        return sb.toString();
    }

    /**
     * byteArr转String
     *
     * @param bytes 字节数组
     * @return 字符串
     */
    public static String bytes2String(byte[] bytes) {
        if (bytes == null) return null;
        int len = bytes.length;
        if (len <= 0) return null;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < len; i++) {
            if(0x00 != bytes[i]){
                sb.append((char) (bytes[i] & 0xff));
            }
        }
        return sb.toString();
    }

    public static float getTempture(byte[] bytes) {
        float preNum = bytes[2];
        float afterNum = bytes[3];
        float decimal = 0;
        if (afterNum >= 100){
            decimal = Float.parseFloat(String.valueOf(preNum).concat(".").concat(String.valueOf(afterNum)));
        }else if (afterNum >= 10 && afterNum <= 99){
            decimal = Float.parseFloat(String.valueOf(preNum).concat(".").concat("0" + String.valueOf(afterNum)));
        }else if (afterNum < 10){
            decimal = Float.parseFloat(String.valueOf(preNum).concat(".").concat("00" + String.valueOf(afterNum)));
        }
        return decimal;
    }
}
